
#include "a9main.h" 

#define N 8

int cgiMain() 
{ 
	key_t key;
	char buf[N];
	
	int msgid;
	CGI_cmd msg_buf;
	M0_cmd m0;
	memset(&msg_buf,0,sizeof(msg_buf));
	
	FILE * fp;
	fp = fopen("./wmrlog", "a");
	cgiFormString("led",buf,N);
	

	if((key = ftok("/app", 'g')) < 0)
	{
		perror("ftok");
		exit(1);
	}
#if 0
	if((msgid = msgget(key, 0666)) < 0)
	{
		perror("msgget");
		exit(1);
	}
#endif
	msgid = msgget(key, IPC_CREAT|IPC_EXCL|0666);

	if(msgid == -1)
	{
		if(errno == EEXIST)
		{
			msgid = msgget(key,0666);
		}
		else{
			perror("msgget");
			exit(1);
		}
	}
	bzero (msg_buf.text, sizeof(msg_buf.text));

    msg_buf.mytype = 1;
	msg_buf.type = M0_ctl;
	if (buf[0] == '1')
	{
		m0.dev=LED;
		m0.command = ON;
//		fprintf(fp, "%d  %s\n", __LINE__, __func__);
		memcpy(&msg_buf.text[0],&m0,sizeof(m0));
	}
	else
	{
		m0.dev=LED;
		m0.command = OFF;
 //     fprintf(fp, "%d  %s\n", __LINE__, __func__);
		memcpy(&msg_buf.text[0],&m0,sizeof(m0));
	}
	msgsnd(msgid, &msg_buf,sizeof(msg_buf)-sizeof(long),0);

	cgiHeaderContentType("text/html\n\n"); 
	fprintf(cgiOut, "<HTML><HEAD>\n"); 
	fprintf(cgiOut, "<TITLE>My CGI</TITLE></HEAD>\n"); 
	fprintf(cgiOut, "<BODY>"); 

	fprintf(cgiOut, "<H2>send sucess</H2>");

	//fprintf(cgiOut, "<a href='.html'>返回</a>"); 
	fprintf(cgiOut, "<meta http-equiv=\"refresh\" content=\"1;url=../m0_1.html\">");
	fprintf(cgiOut, "</BODY>\n"); 
	fprintf(cgiOut, "</HTML>\n"); 


	return 0; 
} 
